package com.cyh.exp.controller;


import com.cyh.exp.mode.WsMessage;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
//@EnableScheduling
@RestController
public class WebSocketController {


    private SimpMessagingTemplate template;
    public WebSocketController(SimpMessagingTemplate template){
        this.template = template;
    }

    @Scheduled(fixedRate = 20000)
    public void sendTopicMessage(){
        System.out.println("后端广播推送！");
        int id = (int) (Math.random()*1000);
        WsMessage wm = new WsMessage(
                id,"server",new Date(),"广播消息："+id
        );
        this.template.convertAndSend("/topic/getResponse",wm);
    }

    public void sendQueueMessage(){
        System.out.println("后端点对点推送");
        WsMessage wm = new WsMessage(
                1,"server",new Date(),"点对点消息："+1
        );
        this.template.convertAndSendToUser("1","/getResponse",wm);
    }

    @MessageMapping("/hello")
    @SendTo("/topic/getResponse")
    public WsMessage chat(WsMessage message){
        System.out.println(String.format("id:%d,name:%s,date:%s,content:%s",message.getId(),message.getName(),message.getTime(),message.getContent()));
        return message;
    }


}
